<?php

/**
 * Description of Web
 *
 * @author ananda
 */
class App_Console extends App
{
    /**
     * 可选项默认值
     */
    const OPT_DEFAULT = '|OPT-DEF|';

    /**
     * 传递进来的参数
     * @var array
     */
    protected $argv;

    /**
     * 传递进来的参数数量
     * @var integer
     */
    protected $argc;

    /**
     * 解析出来的可选项列表
     * 均去掉了首字-
     * @var array
     */
    public $options = array();

    public function init() {}

    public function main($options = array())
    {
        // 解析指令
        $this->route();

        // 创建控制器
        $this->controller = $this->createController($this->controller);

        // 创建ACTION
        $this->action = $this->createAction($this->controller, $this->action, $this->params);

        $this->action->main();
    }

    public function route()
    {
        $this->argv = $_SERVER['argv'];
        unset($this->argv[0]);
        $this->argc = $_SERVER['argc'];

        for ($i = 1; $i < $this->argc; $i++) {
            $param = $this->argv[$i];
            if ($param[0] === '-') {
                $param = explode('=', substr($param, 1));
                $this->options[$param[0]] = isset($param[1]) ? $param[1] : self::OPT_DEFAULT;
            } else {
                if (empty($this->controller)) {
                    $this->controller = ucfirst($param);
                } elseif (empty($this->action)) {
                    $this->action = ucfirst(strtolower($param));
                } else {
                    $this->params[] = $param;
                }
            }
        }

        empty($this->controller) && ($this->controller = ucfirst(Com::glob('com.default_controller')));
    }

}
